<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
                v-model="searchForm.className"
                placeholder="教学班名称"
                clearable
                size="small"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
            <el-button size="small" @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 教学班列表 -->
      <el-table :data="classList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="教学班名称" />
        <el-table-column label="学生人数" width="100">
          <template #default="scope">
            {{ classStudentsMap[scope.row.id]?.length || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.createdTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewStudents(scope.row)">查看学员</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            background
            layout="prev, pager, next"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 学员列表对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="currentClass ? `${currentClass.name}的学员列表` : '学员列表'"
        width="60%"
    >
      <el-table :data="studentList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="stuName" label="学生姓名" />
        <el-table-column prop="currentGrade" label="年级" />
        <el-table-column prop="fromPlace" label="来源地址" />
        <el-table-column prop="parentPhone" label="监护人电话" />
        <el-table-column prop="isFirst" label="是否新生">
          <template #default="scope">
            {{ scope.row.isFirst === '1' ? '是' : '否' }}
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'

export default {
  name: 'TeacherClass',
  setup() {
    const searchForm = reactive({
      className: ''
    })
    const classList = ref([])
    const studentList = ref([])
    const classStudentsMap = ref({})
    const currentClass = ref(null)
    const dialogVisible = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    return {
      searchForm,
      classList,
      studentList,
      classStudentsMap,
      currentClass,
      dialogVisible,
      currentPage,
      pageSize,
      total
    }
  },
  created() {
    this.fetchClasses()
  },
  methods: {
    // 获取教学班列表
    async fetchClasses() {
      try {
        const teacherId = this.$store.getters.getUser.id
        const res = await this.$axios.get('/manager-class/teacher-classes', {
          params: {
            teacherId,
            className: this.searchForm.className,
            currentPage: this.currentPage,
            pageSize: this.pageSize
          },
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })

        if (res.data.code === 200) {
          const data = res.data.data
          this.classList = data.records
          this.total = data.total

          // 获取每个班级的学生数量
          for (const classItem of this.classList) {
            await this.fetchClassStudentsCount(classItem.id)
          }
        }
      } catch (error) {
        console.error('获取教学班列表失败:', error)
        this.$message.error('获取教学班列表失败')
      }
    },

    // 获取班级学生数量
    async fetchClassStudentsCount(classId) {
      try {
        const res = await this.$axios.get(`/manager-class/students/${classId}`, {
          headers: {
            Authorization: localStorage.getItem("token")
          }
        })

        if (res.data.code === 200) {
          // 直接赋值，不需要使用 $set
          this.classStudentsMap[classId] = res.data.data
        }
      } catch (error) {
        console.error('获取学生数量失败:', error)
      }
    },

    // 查看学员列表
    async viewStudents(classInfo) {
      this.currentClass = classInfo
      this.dialogVisible = true
      this.studentList = this.classStudentsMap[classInfo.id] || []
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchClasses()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.className = ''
      this.handleSearch()
    },

    // 分页
    handlePageChange(page) {
      this.currentPage = page
      this.fetchClasses()
    },

    // 格式化日期
    formatDate(date) {
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>